<template>
  <CdModal v-model="computedModelValue" :title="fullTitle" width="300">
    <template #header>
      {{ fullTitle }}
      <div class="header-extra">
        <Poptip trigger="hover" title="提示" placement="top-start" transfer>
          <Icon type="md-help-circle" size="18" class="text-info" /><span class="text-info">帮助提示</span>
          <template #content>
            <div>1.勾选展示字段，可设置字段是否在页面上展示</div>
            <div>2.上下拖动字段名称，可调整字段在页面上的显示位置</div>
            <div>3.勾选冻结字段，左右拖动视图时，该字段及该字段之前字段将始终显示在页面上</div>
          </template>
        </Poptip>
      </div>
    </template>

    <Table
      ref="userConfigTableRef"
      size="small"
      :height="props.tableHeight"
      :draggable="props.draggable"
      :loading="tableOptions.loading"
      :columns="tableOptions.columns"
      :data="tableOptions.tableData"
      :border="true"
      :show-header="true"
      @on-selection-change="onSelectionChangeHandle"
      @on-drag-drop="onDragDropHandle"
    ></Table>

    <template #footer>
      <Button type="primary" :loading="saveLoading" @click="onRestConfigHandle">还原初始配置</Button>
      <Button class="ml10" type="primary" :loading="saveLoading" @click="onSaveHandle">保 存</Button>
    </template>
  </CdModal>
</template>

<script setup lang="ts">
import { getTableConfig, getAllSearchFormConfig, userFormConfigSave, userFormConfigDelete } from '@/api/common'
import CdModal from '@/components/basic/CdModal'
import { isNotEmpty } from '@/utils/baseTool'
import { ColorPicker, Checkbox } from 'view-ui-plus'
import { computed, nextTick, onBeforeMount, reactive, ref } from 'vue'
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  id: {
    type: String,
    default: ''
  },
  title: {
    type: String,
    default: ''
  },
  draggable: {
    type: Boolean,
    default: true
  },
  tableHeight: {
    // 表格高度
    type: String,
    default: '350'
  },
  type: {
    // 视图类型，0：条件  1：表头
    type: String,
    default: '0'
  },
  viewNo: {
    // 视图编号
    type: String,
    required: true
  }
})

const emits = defineEmits(['update:modelValue', 'after-save'])

const computedModelValue = computed({
  get: () => props.modelValue,
  set: () => emits('update:modelValue')
})
// const suffixTitle = computed(() => (props.id ? '详情' : '新建'))
const fullTitle = computed(() => props.title)

interface ITableOptions {
  tableData: any[]
  tableDataHidden: any[]
  columns: any[]
  selectedRows: any[]
  loading: boolean
}
const tableOptions: ITableOptions = reactive({
  tableData: [],
  tableDataHidden: [],
  columns: [],
  selectedRows: [],
  loading: false
})

// 表头定义
const getTableColumnsHandle = () => {
  tableOptions.columns = [
    {
      type: 'selection',
      width: 50,
      align: 'center'
    },
    {
      title: '字段名称',
      key: 'comments'
    }
  ]

  if (props.type === '1') {
    tableOptions.columns.push(
      {
        title: '字段文字颜色',
        width: 100,
        key: 'labelColor',
        align: 'center',
        render: (h: any, { row, index }: any) => {
          if (!row.labelColor) {
            row.labelColor = '#000000'
          }
          return h('div', [
            h(
              ColorPicker,
              {
                modelValue: row.labelColor,
                colors: [
                  '#2D8CF0',
                  '#19BE6B',
                  '#FF9900',
                  '#ED4014',
                  '#00B5FF',
                  '#19C919',
                  '#F9E31C',
                  '#EA1A1A',
                  '#9B1DEA',
                  '#00C2B1',
                  '#AC7A33',
                  '#1D35EA',
                  '#8BC34A',
                  '#F16B62',
                  '#EA4CA3',
                  '#0D94AA',
                  '#FEBD79',
                  '#5D4037',
                  '#00BCD4',
                  '#F06292',
                  '#CDDC39',
                  '#607D8B',
                  '#000000',
                  '#FFFFFF'
                ],
                transfer: true,
                'onOn-change': (value: string) => {
                  nextTick(() => {
                    tableOptions.tableData[index]._checked = row._checked
                    tableOptions.tableData[index].labelColor = value
                  })
                }
              },
              ''
            )
          ])
        }
      },
      {
        title: '冻结字段',
        width: 80,
        key: 'isFreeze',
        align: 'center',
        render: (h: any, { row, index }: any) => {
          return h(
            Checkbox,
            {
              modelValue: row.isFreeze,
              checked: row.isFreeze === '1',
              'true-value': '1',
              'false-value': '0',
              'onOn-change': (value: any) => {
                tableOptions.tableData[index]._checked = row._checked
                tableOptions.tableData[index].isFreeze = value
              }
            },
            ''
          )
        }
      }
    )
  }
}

// 数据加载
let viewId = ''
const loadDataHandle = () => {
  if (!isNotEmpty(props.viewNo)) {
    return window.$Message.warning('视图编号不存在')
  }
  tableOptions.loading = true
  const apiFunc = props.type === '0' ? getAllSearchFormConfig : getTableConfig
  apiFunc(props.viewNo).then((res) => {
    const { isSuccess, errorMsg, errmsg, data } = res
    if (isSuccess) {
      tableOptions.tableData = []
      tableOptions.tableDataHidden = []
      viewId = data.id
      if (data.columns) {
        let columns = data.columns.map((column: any) => ({ ...column, _checked: column.isChecked }))
        for (const column of columns) {
          if (column.showType !== 'hidden') {
            tableOptions.tableData.push(column)
          } else {
            tableOptions.tableDataHidden.push(column)
          }
        }
      }
    } else {
      window.$Message.error(errorMsg || errmsg)
    }
    tableOptions.loading = false
  })
}

// 表格选择回调
const onSelectionChangeHandle = (selection: any) => {
  tableOptions.selectedRows = selection
}

// 拖拽回调
const onDragDropHandle = (index1: number, index2: number) => {
  tableOptions.tableData.splice(index2, 0, tableOptions.tableData.splice(index2 + (index1 - index2), 1)[0])
}

// 保存
const saveLoading = ref(false)
const onSaveHandle = () => {
  const params: any = { viewId }
  let dataList = []
  if (tableOptions.selectedRows.length > 0) {
    // 将隐藏字段返回给数据列表
    dataList = [...tableOptions.selectedRows, ...tableOptions.tableDataHidden]
    for (let i = 0; i < dataList.length; i++) {
      const row = dataList[i]
      const preName = `columnList[${i}]`
      params[`${preName}.id` as keyof typeof params] = ''
      params[`${preName}.viewCol.column.id` as keyof typeof params] = row.id
      params[`${preName}.viewCol.column.name` as keyof typeof params] = row.name
      params[`${preName}.labelColor` as keyof typeof params] = row.labelColor
      params[`${preName}.isFreeze` as keyof typeof params] = row.isFreeze
      params[`${preName}.sort` as keyof typeof params] = i
    }
    saveLoading.value = true
    userFormConfigSave(params).then(
      (res) => {
        const { isSuccess, errorMsg, errmsg } = res
        if (isSuccess) {
          window.$Message.success('保存成功')
          onCancelHandle()
          emits('after-save', props.type)
        } else {
          window.$Message.errorMsg(errorMsg || errmsg)
        }
        saveLoading.value = false
      },
      () => {
        saveLoading.value = false
      }
    )
  }
}

// 还原设置
const onRestConfigHandle = () => {
  saveLoading.value = true
  userFormConfigDelete(viewId).then(
    (res) => {
      const { isSuccess, errorMsg, errmsg } = res
      if (isSuccess) {
        onCancelHandle()
        emits('after-save', props.type)
      } else {
        window.$Message.error(errorMsg || errmsg)
      }
      saveLoading.value = false
    },
    () => {
      saveLoading.value = false
    }
  )
}

const onCancelHandle = () => emits('update:modelValue', false)

onBeforeMount(() => {
  getTableColumnsHandle()
  loadDataHandle()
})
</script>
<style scoped>
.header-extra {
  position: absolute;
  top: 0;
  right: 30px;
  cursor: pointer;
}
</style>
